import { View } from "@tarojs/components";
import { PropsWithChildren, ReactNode, useEffect, useState } from "react";
import "./index.less";

interface IProps extends PropsWithChildren {
  actions: ReactNode;
  id: string;
  open?: boolean;
  onMove?: (flag: boolean) => void;
}
export const SwipeAction = (props: IProps) => {
  const { actions, children, id, open, onMove } = props;
  const [org, setOrg] = useState(0);
  const [movePx, setMovePx] = useState(0)

  const onMoveEle = (e) => {
    const cur = e.touches[0]?.screenX;
    onMove?.(cur - org < -10)
    // 左滑
    if (cur - org < -10) {
      // TODO: 左移的距离最好是actions元素的宽度
      // Taro.createSelectorQuery().select(`#${id}`).boundingClientRect().exec(
      //   (rect) => {
      //     console.log(rect);
      //   }
      // );
      setMovePx(-120 - 30);
    } else {
      setMovePx(0);
    }
  }

  const onOpenChange = (flag: boolean) => {
    if (flag) {
      setMovePx(-120 - 30);
    } else {
      setMovePx(0);
    }
  }

  useEffect(() => {
    if (open !== undefined) {
      onOpenChange(open)
    }
  }, [open]);

  return (
    <View onClick={() => onOpenChange(false)} id={id} style={{transform: `translateX(${movePx}px)`}} className="taro-swipe-action" onTouchStart={(e) => setOrg((e as any).touches[0].screenX)} onTouchMove={(e) => onMoveEle(e)} onTouchEnd={(e) => setOrg(0)}>
      <View className="children-wrapper">{children}</View>
      <View style={{ width: 120}}>{actions}</View>
    </View>
  );
};
